package com.zb.nio.channel;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author: zhaobin
 * @date: 2023/12/23 12:18
 * @Description:
 */
public class FileChannelDemo1 {

    /**
     * FileChanel读取数据到buffer中
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // 创建FileChannel
        RandomAccessFile file = new RandomAccessFile("./src/main/resources/01.txt", "rw");
        FileChannel channel = file.getChannel();

        // 创建Buffer
        ByteBuffer buf = ByteBuffer.allocate(1024);

        // 把数据读入Buffer
        int bytesRead = channel.read(buf);
        while (bytesRead != -1) {
            System.out.println("\n读取了："+bytesRead);
            // 读写切换
            buf.flip();
            // 如果buf中有剩余数据就一直输出
            while(buf.hasRemaining()){
                System.out.print((char)buf.get());
            }
            buf.clear();
            // 继续下次读取
            bytesRead = channel.read(buf);
        }
        // file.close();
        // channel关闭后，file也会关闭
        channel.close();
        System.out.println("\n操作结束！");
    }
}
